package com.milo.java7.reflect.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author: Milogenius
 * @create: 2019-08-12 16:31
 * @description:
 **/
public class CGlibProxy implements MethodInterceptor {
    private static CGlibProxy instance = new CGlibProxy();

    /**
     * 单例模式
     */
    private CGlibProxy() {
    }

    public static CGlibProxy getCGlibProxy() {
        return instance;
    }

    private void before() {
        System.out.println("this is before function");
    }

    private void after() {
        System.out.println("this is after function");
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before();
        Object result = methodProxy.invokeSuper(o, objects);
        after();
        return result;
    }

    public <T> T getProxy(Class<T> cls) {
        return (T) Enhancer.create(cls, this);
    }
}
